
const defaultState = {
    // 当前选中文件
    current: 0,

    // 打开文件
    opened: []
};

/**
 * 切换当前文件
 * @type {String}
 */
export const SWITCH_ACTIVE_FILE = 'SWITCH_ACTIVE_FILE';

/**
 * 添加新文件并设为当前
 * @type {String}
 */
export const ADD_FILE = 'ADD_FILE';

/**
 * 读取文件
 * @type { String}
 */
export const READ_FILE = 'READ_FILE';

/**
 * 关闭文件
 * @type {String}
 */
export const CLOSE_FILE = 'CLOSE_FILE';

/**
 * 创建文件夹
 * @type {String}
 */
export const CREATE_DIR = 'CREATE_DIR';

/**
 * 删除文件夹/文件
 * @type {String}
 */
export const DELETE_PATH = 'DELETE_PATH';

/**
 * 重命名文件夹/文件
 * @type {String}
 */
export const MOVE_PATH = 'MOVE_PATH';

/**
 * 创建文件
 * @type {String}
 */
export const CREATE_FILE = 'CREATE_FILE';

/**
 * 保存文件
 * @type {String}
 */
export const SAVE_FILE = 'SAVE_FILE';

/**
 * 标记文件是否修改过
 * @type {String}
 */
export const MARK_DIRTY = 'MARK_DIRTY';

/**
 * 打开的文件
 * @param {Object} state
 * @param {Object} action
 */
export default function fileReducer(state = defaultState, action) {
    let index;

    switch (action.type) {
        // 切换当前文件
        case SWITCH_ACTIVE_FILE:
            return {
                ...state,
                current: action.payload
            };

        // 添加新文件并设为当前
        case ADD_FILE:
            return {
                ...state,
                opened: [
                    ...state.opened,
                    action.payload
                ],
                current: state.opened.length
            };

        // 移除打开文件
        case CLOSE_FILE:
            if (action.payload <= state.current) {
                // 关闭当前标签左侧标签, 序号顺序减一
                index = state.current > 0 ? state.current - 1 : 0;
            } else {
                // 关闭当前标签右侧标签, 序号不变
                 index = state.current;
            }

            return {
                ...state,
                opened: state.opened.filter(
                    (item, index) => index !== action.payload),
                current: index
            };

        // 标记文件是否修改过
        case MARK_DIRTY:
            return {
                ...state,
                opened: state.opened.map(item => {
                    return item.path === action.payload.path ?
                        {
                            ...item,
                            dirty: action.payload.dirty
                        } : item;
                })
            };

        default:
            return state;
    }
}